import express from 'express';
import { Server } from '../models/Server.js';
import { AccessLog } from '../models/AccessLog.js';
import { authenticate } from '../middleware/auth.js';
import { log } from '../utils/logger.js';

const router = express.Router();

// 所有路由都需要认证
router.use(authenticate);

/**
 * 获取所有服务器配置
 */
router.get('/', async (req, res) => {
  try {
    const servers = await Server.getAllByUser(req.user.id);
    
    log.info(`获取服务器列表`, { userId: req.user.id, count: servers.length });
    
    res.json({
      success: true,
      data: servers
    });
  } catch (error) {
    log.error('获取服务器列表失败', { error: error.message, userId: req.user.id });
    res.status(500).json({
      success: false,
      message: '获取服务器列表失败'
    });
  }
});

/**
 * 获取单个服务器配置
 */
router.get('/:id', async (req, res) => {
  try {
    const serverId = parseInt(req.params.id);
    const server = await Server.getById(serverId, req.user.id);
    
    if (!server) {
      return res.status(404).json({
        success: false,
        message: '服务器不存在'
      });
    }
    
    log.info(`获取服务器配置`, { userId: req.user.id, serverId });
    
    res.json({
      success: true,
      data: server
    });
  } catch (error) {
    log.error('获取服务器配置失败', { error: error.message, userId: req.user.id });
    res.status(500).json({
      success: false,
      message: '获取服务器配置失败'
    });
  }
});

/**
 * 创建服务器配置
 */
router.post('/', async (req, res) => {
  try {
    let { name, host, port, username, authType, password, privateKey, groupName, expireDate } = req.body;
    
    // 验证必填字段
    if (!name || !host || !username) {
      return res.status(400).json({
        success: false,
        message: '服务器名称、主机地址和用户名不能为空'
      });
    }
    
    if (!password && !privateKey) {
      return res.status(400).json({
        success: false,
        message: '密码或私钥至少需要提供一个'
      });
    }
    
    // 创建服务器
    const serverId = await Server.create(req.user.id, {
      name,
      host,
      port,
      username,
      authType,
      password,
      privateKey,
      groupName,
      expireDate
    });
    
    // 记录日志
    AccessLog.create(
      req.user.id,
      req.clientIP,
      '创建服务器',
      `创建服务器配置: ${name} (${host})`,
      req.get('user-agent')
    );
    
    log.info(`创建服务器配置成功`, { userId: req.user.id, serverId, name });
    
    res.json({
      success: true,
      message: '服务器配置创建成功',
      data: { id: serverId }
    });
  } catch (error) {
    log.error('创建服务器配置失败', { error: error.message, userId: req.user.id });
    res.status(500).json({
      success: false,
      message: '创建服务器配置失败'
    });
  }
});

/**
 * 更新服务器配置
 */
router.put('/:id', async (req, res) => {
  try {
    const serverId = parseInt(req.params.id);
    const updates = req.body;
    
    // 转换驼峰命名为下划线命名
    if (updates.expireDate !== undefined) {
      updates.expire_date = updates.expireDate;
      delete updates.expireDate;
    }
    if (updates.authType !== undefined) {
      updates.auth_type = updates.authType;
      delete updates.authType;
    }
    if (updates.privateKey !== undefined) {
      updates.private_key = updates.privateKey;
      delete updates.privateKey;
    }
    if (updates.groupName !== undefined) {
      updates.group_name = updates.groupName;
      delete updates.groupName;
    }
    if (updates.sortOrder !== undefined) {
      updates.sort_order = updates.sortOrder;
      delete updates.sortOrder;
    }
    
    // 删除不应更新的字段
    delete updates.id;
    delete updates.user_id;
    delete updates.created_at;
    delete updates.updated_at;
    
    const success = await Server.update(serverId, req.user.id, updates);
    
    if (!success) {
      return res.status(404).json({
        success: false,
        message: '服务器不存在或更新失败'
      });
    }
    
    // 记录日志
    AccessLog.create(
      req.user.id,
      req.clientIP,
      '更新服务器',
      `更新服务器配置: ID ${serverId}`,
      req.get('user-agent')
    );
    
    log.info(`更新服务器配置成功`, { userId: req.user.id, serverId });
    
    res.json({
      success: true,
      message: '服务器配置更新成功'
    });
  } catch (error) {
    console.error('❌ 更新服务器配置错误:', error);
    log.error('更新服务器配置失败', { 
      error: error.message,
      code: error.code,
      sql: error.sql,
      userId: req.user.id,
      serverId: req.params.id,
      updates: JSON.stringify(req.body)
    });
    res.status(500).json({
      success: false,
      message: error.message || '更新服务器配置失败'
    });
  }
});

/**
 * 删除服务器配置
 */
router.delete('/:id', async (req, res) => {
  try {
    const serverId = parseInt(req.params.id);
    const success = await Server.delete(serverId, req.user.id);
    
    if (!success) {
      return res.status(404).json({
        success: false,
        message: '服务器不存在'
      });
    }
    
    // 记录日志
    AccessLog.create(
      req.user.id,
      req.clientIP,
      '删除服务器',
      `删除服务器配置: ID ${serverId}`,
      req.get('user-agent')
    );
    
    log.info(`删除服务器配置成功`, { userId: req.user.id, serverId });
    
    res.json({
      success: true,
      message: '服务器配置删除成功'
    });
  } catch (error) {
    log.error('删除服务器配置失败', { error: error.message, userId: req.user.id });
    res.status(500).json({
      success: false,
      message: '删除服务器配置失败'
    });
  }
});

/**
 * 获取服务器分组
 */
router.get('/groups/list', (req, res) => {
  try {
    const groups = Server.getGroupsByUser(req.user.id);
    
    res.json({
      success: true,
      data: groups
    });
  } catch (error) {
    log.error('获取服务器分组失败', { error: error.message, userId: req.user.id });
    res.status(500).json({
      success: false,
      message: '获取服务器分组失败'
    });
  }
});

export default router;

